import React from 'react';
import { success, error, Button, Modal, Tabs, Link, info, Table, TitleBar } from '../../../ui-components';
import style from './style.onboarding-inviting';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import { addOldUser, delStaff, reInviteImportedUser, resetOnboardingFlows, fetchOnboardingImportedUsers } from '../../../actions/onboarding.hr.action'
import { map as tableMap } from '../../../ui-components/table'
import util from '../../../util';
import { LabelInput } from 'sq-ui';
import rule from '../../../libs/rule';

export default
@connect(({ onboardingFlowsHr }) => ({ onboardingFlowsHr }), dispatch => ({actions: bindActionCreators({ fetchOnboardingImportedUsers, resetOnboardingFlows, reInviteImportedUser, delStaff, addOldUser }, dispatch)}))
class HrOnboardingInviting extends React.Component {

    pageNumber=1
    pageSize=30

    init = {
        delInvitation: false,
        invitation: false,
        invitedUser: {},
        addOldUser: false,
        oldUser: {
            fullName: '',
            emailAddress: '',
            mobilePhone: '',
        },
    }

    state = {
        ...this.init
    }

    static contextTypes = {
        router: React.PropTypes.object
    }

    reInvite() {
        const { userId } = this.state.invitedUser
        info('发送中...')
        this.props.actions.reInviteImportedUser(userId, () => {
            success('发送成功!');
        })
        this.cancelReInvite();
    }

    delInvite() {
        const { userId } = this.state.invitedUser;
        info('删除中...');
        this.props.actions.delStaff(userId, () => {
            success('删除成功!');
            this.fetchOnboardingImportedUsers()
        })
        this.cancelDelInvite();
    }

    requestReInvite(user) {
        this.setState({
            invitation: true,
            invitedUser: user
        })
    }

    requestDelInvite(user) {
        this.setState({
            delInvitation: true,
            invitedUser: user
        })
    }

    cancelReInvite() {
        this.setState({
            ...this.init
        })
    }

    cancelDelInvite() {
        this.setState({
            ...this.init
        })
    }

    handleTabChange(index) {
        const { isActivated, ...others } = this.props.location.query
        this.context.router.push(`/hr/settings/onboarding-inviting?isActivated=${index-2}&${util.body(others)}`)
    }

    handlePageChage(_pageNumber) {
        const { pageNumber, ...others } = this.props.location.query
        this.context.router.push(`/hr/settings/onboarding-inviting?pageNumber=${_pageNumber}&${util.body(others)}`)
    }

    fetchOnboardingImportedUsers(props) {
        props = props || this.props
        const pageNumber = props.location.query.pageNumber || this.pageNumber

        info('读取中..', true)
        this.props.actions.fetchOnboardingImportedUsers({
            pageNumber,
            pageSize: this.pageSize,
            isActivated: props.location.query.isActivated
        }, () => {
            info()
        })
    }

    // 请求添加现有员工
    requestAddOldUser() {
        this.setState({
            addOldUser: true,
        });
    }

    cancelAddOldUser() {
        this.setState({
            addOldUser: false,
            oldUser: this.init.oldUser,
        });
    }

    // 添加现有员工
    addOldUser() {
        const { fullName, emailAddress, mobilePhone } = this.state.oldUser;
        if (!fullName.trim()) return error('姓名不能为空!');

        if (!emailAddress.trim()) return error('邮箱不能为空!');
        if (!rule.emailAddress.regex.test(emailAddress))  return error(rule.emailAddress.msg);

        // if (!mobilePhone.trim()) return error('手机号不能为空!');
        // if (!rule.mobilePhone.regex.test(mobilePhone)) return error(rule.mobilePhone.msg);

        if (mobilePhone.trim()) {
            if (!rule.mobilePhone.regex.test(mobilePhone)) return error(rule.mobilePhone.msg);
        }

        this.props.actions.addOldUser(this.state.oldUser, () => {
            success('邀请成功!');
            this.props.actions.fetchOnboardingImportedUsers({
                pageNumber: 1,
                pageSize: this.pageSize,
                isActivated: this.props.location.query.isActivated,
            });
        });
        this.cancelAddOldUser();
    }

    updateOldUser(name) {
        return e => {
            this.setState({
                oldUser: {
                    ...this.state.oldUser,
                    [name]: e.target.value,
                }
            })
        }
    }

    componentWillReceiveProps(props) {
        if (props.location.query.isActivated != this.props.location.query.isActivated) {
            this.fetchOnboardingImportedUsers(props)
        }
    }

    componentWillUnmount() {
        this.props.actions.resetOnboardingFlows();
    }

    componentDidMount() {
        this.fetchOnboardingImportedUsers()
    }

    render() {

        const { importedUser } = this.props.onboardingFlowsHr
        const { totalNumber, coreUserProfileVOs } = importedUser
        const { isActivated } = this.props.location.query
        const tableConfig = {
            pagin: typeof totalNumber === 'number' && {
                pageSize: this.pageSize,
                pageNumber: this.props.location.query.pageNumber || this.pageNumber,
                totalNumber,
                onChange: ::this.handlePageChage,
                fetch: ::this.fetchOnboardingImportedUsers
            },
            data: coreUserProfileVOs,
            model: {
                fullName: '成员',
                status: '帐号状态',
                createdTime: '邀请时间',
                others: ''
            },
            config: {
                fullName: '.4',
                createdTime: '.3',
                status: '.3',
                others: '.5'
            },
            map: {
                fullName: tableMap.fullName,
                createdTime: v => util.time(v),
                status: (_, { userEmploymentVO }) => {
                    const { userStatus } = userEmploymentVO
                    return <span style={{ width: '45px', lineHeight: '20px',textAlign: 'center', display: 'inline-block', color: '#fff', fontSize: '12px', height: '20px' }} className={style[`user-status-${userStatus}`]}>{userStatus == 2? '待激活': '已激活'}</span>
                },
                others: (_, user) => user.userEmploymentVO.userStatus == 2? (
                    <span data-role="table-hover">
            <Link label="重发邀请邮件" onClick={() => this.requestReInvite(user)} />
            <Link style={{ marginLeft: '10px' }} label="删除帐号" color="red" onClick={() => this.requestDelInvite(user)} />
          </span>
                ): null
            },
        }
        return (
            <div className={style.root}>
                <TitleBar
                    label="邀请员工"
                    actions={[
                        {
                            label: '新增邀请',
                            blue: true,
                            onClick: ::this.requestAddOldUser,
                        },
                        {
                            label: '批量操作',
                            onClick: () => this.context.router.push('/hr/settings/profile-upload'),
                            blueLine: true,
                        }
                    ]}
                />
                <Tabs
                    className={style.tabs}
                    top
                    index={+isActivated+2}
                    onChange={::this.handleTabChange}
                    tabs={[
                        {
                            label: '全部',
                        },
                        {
                            label: '帐号待激活',
                        },
                        {
                            label: '帐号已激活'
                        }
                    ]}
                />
                <Table
                    {...tableConfig}
                />
                {
                    totalNumber === 0?
                        <Link style={{ border: '1px solid #00a0f6', color: '#00a0f6', textAlign: 'center',display: 'block', lineHeight: '40px', width: '130px', height: '40px', margin: '15px auto' }} label="新增邀请" to={'#/hr/settings/profile-upload'}/>: null
                }
                <Modal
                    active={this.state.invitation}
                    onRequestClose={::this.cancelReInvite}
                    actions={[
                        'cancel',
                        ::this.reInvite
                    ]}
                    title="重新发送邀请"
                >
                    <div>
                        <p style={{ marginBottom: '15px' }}>确认重新发送邀请邮件给该用户吗？</p>
                    </div>
                </Modal>
                <Modal
                    active={this.state.delInvitation}
                    onRequestClose={::this.cancelDelInvite}
                    actions={[
                        'cancel',
                        ::this.delInvite
                    ]}
                    title="删除帐号"
                >
                    <div>
                        <p style={{ marginBottom: '15px' }}>确认删除该帐号吗？</p>
                    </div>
                </Modal>
                <Modal
                    active={this.state.addOldUser}
                    onRequestClose={::this.cancelAddOldUser}
                    actions={[
                        'cancel',
                        ::this.addOldUser
                    ]}
                    title="邀请员工激活帐号"
                >
                    <div>
                        <div style = {{marginTop: "10px"}}>
                            <i style={{color:"#F89A9A",float:'left'}}>* </i><LabelInput
                            className={style['label-input']}
                            label="员工姓名"
                            placeholder="姓名"
                            autoFocus
                            required
                            value={this.state.oldUser.fullName || ''}
                            onChange={this.updateOldUser('fullName')}
                        />
                        </div>
                        <div style = {{marginTop: "10px"}}>
                            <i style={{color:"#F89A9A",float:'left'}}>* </i><LabelInput
                            className={style['label-input']}
                            value={this.state.oldUser.emailAddress || ''}
                            onChange={this.updateOldUser('emailAddress')}
                            label="企业邮箱"
                            placeholder="企业邮箱"
                            required
                        />
                        </div>
                        <div style = {{marginTop: "10px"}}>
                            <i style={{visibility:"hidden",float:'left'}}>*</i>
                            <LabelInput
                                className={style['label-input']}
                                value={this.state.oldUser.mobilePhone || ''}
                                onChange={this.updateOldUser('mobilePhone')}
                                label="手机号"
                                placeholder="手机号"
                            />
                        </div>
                    </div>
                </Modal>
            </div>
        );
    }
}
